from multiprocessing import Process
import threading
import time

"""
利用Python实现一个多线程程序

打印时间
在程序中调用time.sleep
将上述多线程程序改为多进程
打印时间
"""


# 多线程任务
class MyThread(threading.Thread):
    def __init__(self, num):
        self.num = num

    def get_time(self, x):
        print('当前执行线程：{} ,当前时间戳：{}, 转化时间为: {}'.format(x, time.time(),
                                                      time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())))
        time.sleep(1)
        print('-------线程：{} 休眠 1s------'.format(x))

    def run(self):
        t_list = []
        for i in range(5):
            t = threading.Thread(target=self.get_time, args=(i,))
            t.start()
            t_list.append(t)

        [t.join() for t in t_list]
        print('线程 done!!!')


# 多进程任务
class MyDaemon(object):

    def __init__(self):
        pass

    def get_time(self, x):
        print('当前执行进程：{} ,当前时间戳：{}, 转化时间为: {}'.format(x, time.time(),
                                                      time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())))
        print('-------进程：{} 休眠 1s------'.format(x))
        time.sleep(1)

    def run(self):
        p_list = []
        for i in range(5):
            p = Process(target=self.get_time, args=(i,))
            p.start()
            p_list.append(p)

        [p.join() for p in p_list]
        print('进程 done!!!')


if __name__ == '__main__':
    my_daemon = MyDaemon()
    my_daemon.run()

    my_thread = MyThread(2)
    my_thread.run()
